package cn.manyufun.myf.ui.comics.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import at.blogc.android.views.ExpandableTextView;
import butterknife.BindView;
import butterknife.OnClick;
import cn.manyufun.myf.R;
import cn.manyufun.myf.bean.BaseBean;
import cn.manyufun.myf.bean.ComicsDetailBean;
import cn.manyufun.myf.bean.NewsSummary;
import cn.manyufun.myf.bean.ReplyBean;
import cn.manyufun.myf.common.base.BaseActivity;
import cn.manyufun.myf.common.commonutils.DisplayUtil;
import cn.manyufun.myf.common.commonutils.ImageLoaderUtils;
import cn.manyufun.myf.common.commonutils.LogUtils;
import cn.manyufun.myf.common.commonutils.ToastUtil;
import cn.manyufun.myf.common.commonutils.UserInfoUtils;
import cn.manyufun.myf.common.commonwidget.LoadingTip;
import cn.manyufun.myf.common.share.UmShare;
import cn.manyufun.myf.ui.comics.adapter.ComicsCommentViewPagerAdapter;
import cn.manyufun.myf.ui.comics.contract.ComicsDetailContract;
import cn.manyufun.myf.ui.comics.fragment.ComicsArticleFragment;
import cn.manyufun.myf.ui.comics.fragment.ComicsCommentFragment;
import cn.manyufun.myf.ui.comics.model.ComicsDetailModel;
import cn.manyufun.myf.ui.comics.presenter.ComicsDetailPresenter;
import cn.manyufun.myf.ui.news.activity.NewsDetailActivity;
import cn.manyufun.myf.ui.user.activity.LoginAct;
import cn.manyufun.myf.widget.MyfSliderView;

import static cn.manyufun.myf.common.commonutils.TimeUtil.getfriendlyTime;
import static cn.manyufun.myf.ui.comics.contract.ComicsDetailContract.ACTION_FOLLOW;
import static cn.manyufun.myf.ui.comics.contract.ComicsDetailContract.ACTION_UNFOLLOW;

public class ComicsDetailActivity extends BaseActivity<ComicsDetailPresenter, ComicsDetailModel> implements ComicsDetailContract.View, ViewPager.OnPageChangeListener {
    public final static String FILTER = "comicid";
    @BindView(R.id.app_bar)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.slider)
    SliderLayout mSlider;
    @BindView(R.id.tv_score)
    TextView mTvScore;
    @BindView(R.id.tv_score_count)
    TextView mTvScoreCount;
    @BindView(R.id.rb_score)
    RatingBar mRbScore;
    @BindView(R.id.loadedTip)
    LoadingTip loadedTip;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout mCollapsingToolbarLayout;
    @BindView(R.id.ll_fab)
    View mLLFab;
    @BindView(R.id.tv_comics_name)
    TextView mTvComicsName;
    @BindView(R.id.tv_comics_from)
    TextView mTvComicsFrom;
    @BindView(R.id.tv_author_name)
    TextView mTvAuthorName;
    @BindView(R.id.tv_update)
    TextView mTvUpdate;
    @BindView(R.id.tv_update_name)
    TextView mTvUpdateName;
    @BindView(R.id.tv_fav_num)
    TextView mTvFavNum;
    @BindView(R.id.tv_view_num)
    TextView mTvViewNum;
    @BindView(R.id.ll_comment)
    View mViewComment;
    @BindView(R.id.ll_article)
    View mViewArticle;
    @BindView(R.id.ll_rating)
    View mRating;
    @BindView(R.id.tv_content)
    ExpandableTextView mTvContent;
    @BindView(R.id.btn_expand_text)
    ImageView mBtnExpand;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.ll_type)
    LinearLayout mTypeLayout;
    @BindView(R.id.toolbar_ic_share)
    ImageView mLLShare;
    @BindView(R.id.btn_follow)
    TextView mBtnFollow;
    @BindView(R.id.ll_my)
    View mLLMy;
    @BindView(R.id.ll_my_comment)
    View mLLMyComment;
    @BindView(R.id.ll_my_article)
    View mLLMyArticle;
    @BindView(R.id.iv_head)
    ImageView mIvHead;
    @BindView(R.id.tv_author_name_my)
    TextView mTvAuthorNameComment;
    @BindView(R.id.tv_like_my_comment)
    TextView mTvLikeComment;
    @BindView(R.id.tv_content_my)
    TextView mTvContentComment;
    @BindView(R.id.tv_publish_time)
    TextView mTvPublishTimeComment;
    @BindView(R.id.iv_head_my_article)
    ImageView mIvHeadArticle;
    @BindView(R.id.tv_author_name_my_article)
    TextView mTvAuthorNameArticle;
    @BindView(R.id.rb_score_article)
    RatingBar mRbScoreArticle;
    @BindView(R.id.tv_like_my_article)
    TextView mTvLikeArticle;
    @BindView(R.id.tv_content_my_article)
    TextView mTvContentArticle;
    @BindView(R.id.tv_comment_my_article)
    TextView mTvCommentNumArticle;
    @BindView(R.id.tv_view_my_article)
    TextView mTvViewNumArticle;
    @BindView(R.id.tv_publish_time_my_article)
    TextView mTvPublishTimeArticle;
    @BindView(R.id.tv_title)
    TextView mTvTitleArticle;
    @BindView(R.id.tv_edit_comment)
    TextView mTvEditComment;
    @BindView(R.id.tv_edit_article)
    TextView mTvEditArticle;
    @BindView(R.id.rb_my_score)
    RatingBar mRbMyScore;
    @BindView(R.id.tv_update_start)
    TextView mTvUpdateInfo;

    @OnClick(R.id.toolbar_ic_share)
    void share() {
        doShare();
    }


    @OnClick(R.id.ll_comment)
    void goEditComment() {
        if (!UserInfoUtils.getInstance().checkLogin()) {
            Bundle bundle = new Bundle();
            bundle.putString(LoginAct.LOGIN_FROM, ComicsDetailActivity.class.getSimpleName());
            LoginAct.startAction(this, bundle);
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putParcelable(EditCommentActivity.INTENT_KEY, mBean);
        if (mBean.getMyReply() != null) {
            bundle.putParcelable(EditCommentActivity.REPLY_INFO, mBean.getMyReply());
        }
        EditCommentActivity.startAction(this, bundle);
    }

    @OnClick(R.id.ll_rating)
    void goEditCommentWithRating() {
        if (!UserInfoUtils.getInstance().checkLogin()) {
            Bundle bundle = new Bundle();
            bundle.putString(LoginAct.LOGIN_FROM, ComicsDetailActivity.class.getSimpleName());
            LoginAct.startAction(this, bundle);
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putParcelable(EditCommentActivity.INTENT_KEY, mBean);
        bundle.putInt(EditCommentActivity.IS_FROM_RATING, 1);
        if (mBean.getMyReply() != null) {
            bundle.putParcelable(EditCommentActivity.REPLY_INFO, mBean.getMyReply());
        }
        EditCommentActivity.startAction(this, bundle);
    }

    @OnClick(R.id.ll_article)
    void goEditArticle() {
        if (!UserInfoUtils.getInstance().checkLogin()) {
            Bundle bundle = new Bundle();
            bundle.putString(LoginAct.LOGIN_FROM, ComicsDetailActivity.class.getSimpleName());
            LoginAct.startAction(this, bundle);
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putLong(EditArticleActivity.INTENT_KEY, mComicsID);
        EditArticleActivity.startAction(this, bundle);
    }

    @OnClick(R.id.btn_expand_text)
    void expandContent(View view) {
        mTvContent.expand();
        view.setVisibility(View.GONE);
    }

    @OnClick(R.id.btn_follow)
    void follow(View view) {
        if (!UserInfoUtils.getInstance().checkLogin()) {
            Bundle bundle = new Bundle();
            bundle.putString(LoginAct.LOGIN_FROM, ComicsDetailActivity.class.getSimpleName());
            LoginAct.startAction(this, bundle);
            return;
        }
        mBtnFollow.setClickable(false);
        int actiontype = mBean.isFollowed() ? ACTION_UNFOLLOW : ACTION_FOLLOW;
        LogUtils.logd("follow1" + actiontype);
        mPresenter.followComicsRequest(actiontype, mBean.getComicId());
    }


    long mComicsID;
    private String[] mTitles;
    private ArrayList<Fragment> mFragments;
    private ComicsArticleFragment comicsArticleFragment;
    private ComicsCommentFragment comicsCommentFragment;
    private ComicsCommentViewPagerAdapter mViewPagerAdapter;
    private ComicsDetailBean mBean;

    public static void startAction(Context context, Bundle bundle) {
        Intent intent = new Intent(context, ComicsDetailActivity.class);
        if (bundle != null)
            intent.putExtras(bundle);
        context.startActivity(intent);
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_comics_detail;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public void initView() {
        SetTranslanteBar();
//        SetStatusBarColor(R.color.white);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        Intent intent = getIntent();
        mComicsID = intent.getLongExtra(FILTER, 0);

        mPresenter.getComicsDetailDataRequest(mComicsID);
    }

    @Override
    public void showLoading(String title) {
        loadedTip.setLoadingTip(LoadingTip.LoadStatus.loading);
    }

    @Override
    public void stopLoading() {
        loadedTip.setLoadingTip(LoadingTip.LoadStatus.finish);
    }

    @Override
    public void showErrorTip(String msg) {
        loadedTip.setLoadingTip(LoadingTip.LoadStatus.error);
        loadedTip.setTips(msg);
    }

    @Override
    public void returnComicsDetailData(final ComicsDetailBean newsSummaries) {
        mBean = newsSummaries;
        mSlider.stopAutoCycle();
//        ImageLoaderUtils.display(this, mIvHead, newsSummaries.getCoverImages().get(0));
        for (String img : newsSummaries.getCoverImages()) {
            MyfSliderView sliderView = new MyfSliderView(this);
            sliderView.setScaleType(BaseSliderView.ScaleType.CenterInside);
            sliderView.image(img);
            mSlider.addSlider(sliderView);
        }
        mTvFavNum.setText(newsSummaries.getFollowNum() + "");
        mTvViewNum.setText(newsSummaries.getViewNum() + "");
        mTvUpdateInfo.setText(newsSummaries.getUpdateInfo());

        mSlider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
        mTvScore.setText(newsSummaries.getScore() + "");
        mTvScoreCount.setText(newsSummaries.getViewNum() + "");
        mRbScore.setRating(newsSummaries.getScore());
        mCollapsingToolbarLayout.setTitleEnabled(true);
        mCollapsingToolbarLayout.setCollapsedTitleGravity(Gravity.START);
        mCollapsingToolbarLayout.setCollapsedTitleTextColor(Color.BLACK);

        mTvComicsName.setText(newsSummaries.getTitle());
        if (TextUtils.isEmpty(newsSummaries.getExclusiveTag()))
            mTvComicsFrom.setVisibility(View.GONE);
        else {
            mTvComicsFrom.setText(newsSummaries.getExclusiveTag());
            mTvComicsFrom.setVisibility(View.VISIBLE);
        }
        mTvAuthorName.setText("原作：" + newsSummaries.getAuthor());
        mTvContent.setText(newsSummaries.getBriefContent());

        if (newsSummaries.isFollowed()) {
            mBtnFollow.setTextColor(getResources().getColor(R.color.black));
            mBtnFollow.setText("已收藏");
        } else {
            mBtnFollow.setTextColor(getResources().getColor(R.color.share_red));
            mBtnFollow.setText("收藏");
        }

        List<String> type = newsSummaries.getComicType();
        mTypeLayout.removeAllViews();
        for (String t : type) {
            TextView tv = (TextView) getLayoutInflater().inflate(R.layout.type_text, null);
            LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            param.setMarginEnd(DisplayUtil.dip2px(5f));
            tv.setLayoutParams(param);
            tv.setText(t);
            mTypeLayout.addView(tv);
        }


        mAppBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                Log.d("STATE", state.name());
                if (state == State.EXPANDED) {

                    mCollapsingToolbarLayout.setTitle("");
                    mLLFab.setVisibility(View.VISIBLE);
                    toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_white_18dp);

                    int flag = getWindow().getDecorView().getSystemUiVisibility()
                            & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                    getWindow().getDecorView().setSystemUiVisibility(flag);
                    //展开状态

                } else if (state == State.COLLAPSED) {
                    toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left_black_18dp);
                    mCollapsingToolbarLayout.setTitle(newsSummaries.getTitle());
                    mLLFab.setVisibility(View.GONE);
                    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                    //折叠状态

                } else {

                    //中间状态

                }
            }
        });

        initMyCommentInfo(newsSummaries);
        initViewPager(newsSummaries);
    }

    private void initMyCommentInfo(ComicsDetailBean comicsDetailBean) {
        if (comicsDetailBean.getMyScore() > 0)
            mRbMyScore.setRating(comicsDetailBean.getMyScore());
        if (comicsDetailBean.getMyArticle() != null || comicsDetailBean.getMyReply() != null) {
            mLLMy.setVisibility(View.VISIBLE);
            if (comicsDetailBean.getMyReply() != null) {
                mTvEditComment.setText("修改短评");
                ReplyBean replyBean = comicsDetailBean.getMyReply();
                ImageLoaderUtils.displayRound(this, mIvHead, replyBean.UserImageUrl);
                mTvAuthorNameComment.setText(replyBean.UserName);
                mTvLikeComment.setText(replyBean.LikeNum + "");
                mTvContentComment.setText(replyBean.Content);
                mTvPublishTimeComment.setText(getfriendlyTime(replyBean.ReplyTime.getTime()));
                mLLMyComment.setVisibility(View.VISIBLE);

            } else {
                mLLMyComment.setVisibility(View.GONE);
            }
            if (comicsDetailBean.getMyArticle() != null) {
//                mTvEditArticle.setText("修改漫评");
                final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                final NewsSummary summary = comicsDetailBean.getMyArticle();
                ImageLoaderUtils.displayRound(this, mIvHeadArticle, summary.getAuthorImageUrl());
                mTvAuthorNameArticle.setText(summary.getAuthorName());
//                if (comicsDetailBean.getMyScore() > 0)
                mRbScoreArticle.setRating(comicsDetailBean.getMyScore());
                mTvLikeArticle.setText(summary.getLikeNum() + "");
                mTvTitleArticle.setText(summary.getTitle());
                mTvContentArticle.setText(summary.getBriefInfo());
                mTvCommentNumArticle.setText(summary.getCommentNum() + "");
                mTvViewNumArticle.setText(summary.getViewNum() + "");
                mTvPublishTimeArticle.setText(getfriendlyTime(summary.getPublishTime()));
                mLLMyArticle.setVisibility(View.VISIBLE);
                mLLMyArticle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Bundle bundle = new Bundle();
                        bundle.putLong(NewsDetailActivity.EXTRA_DATA_ARTICLE_ID, summary.getReferenceId());
                        bundle.putString(NewsDetailActivity.EXTRA_DATA_ARTICLE_TITLE, summary.getTitle());
                        bundle.putString(NewsDetailActivity.EXTRA_DATA_ARTICLE_IMG, summary.getCoverImageUrl());
                        NewsDetailActivity.startAction(mContext, bundle);
                    }
                });
            } else {
                mLLMyArticle.setVisibility(View.GONE);
            }
        } else {
            mLLMy.setVisibility(View.GONE);
        }
    }

    @Override
    public void returnFollowComics(BaseBean baseBean, int actionType) {
        LogUtils.logd("followreturn" + actionType);
        if (baseBean.getSuccess().equals(BaseBean.SUCCESS)) {
            if (actionType == ACTION_FOLLOW) {
                mBean.setFollowed(true);
                mBtnFollow.setTextColor(getResources().getColor(R.color.black));
                mBtnFollow.setText("已收藏");
                showShortToast("收藏成功");
            } else {
                mBean.setFollowed(false);
                mBtnFollow.setTextColor(getResources().getColor(R.color.share_red));
                mBtnFollow.setText("收藏");
                showShortToast("取消成功");
            }

        } else {
            showLongToast("出错了：" + baseBean.getErrorMsg());
        }
        mBtnFollow.setClickable(true);
    }

    @Override
    public void reloadComicsDetail() {
        LogUtils.logd(mComicsID + "xwxtest");
        mPresenter.getComicsDetailDataRequest(mComicsID);
    }

    private void initViewPager(ComicsDetailBean newsSummaries) {
        mTitles = new String[]{"短评(" + newsSummaries.getCommentNum() + "条)", "漫评(" + newsSummaries.getArticleNum() + "篇)"};//getResources().getStringArray(R.array.tab_comment);
        //初始化填充到ViewPager中的Fragment集合
        mFragments = new ArrayList<>();
        Bundle args = new Bundle();
        args.putLong("comicsid", mComicsID);
        comicsArticleFragment = ComicsArticleFragment.newInstance(args);
        comicsCommentFragment = ComicsCommentFragment.newInstance(args);

        mFragments.add(comicsCommentFragment);
        mFragments.add(comicsArticleFragment);


        // 初始化ViewPager的适配器，并设置给它
        mViewPagerAdapter = new ComicsCommentViewPagerAdapter(getSupportFragmentManager(), mTitles, mFragments);
        viewpager.setAdapter(mViewPagerAdapter);
        viewpager.setOffscreenPageLimit(2);
        viewpager.addOnPageChangeListener(this);

        tablayout.setTabGravity(TabLayout.GRAVITY_FILL);
        tablayout.setTabMode(TabLayout.MODE_FIXED);
        tablayout.setupWithViewPager(viewpager);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        LogUtils.logd("scrolled" + position + "|" + positionOffset + "|" + positionOffsetPixels);
    }

    @Override
    public void onPageSelected(int position) {
        LogUtils.logd("onPageSelected" + position + "|");
    }

    @Override
    public void onPageScrollStateChanged(int state) {

        LogUtils.logd("onPageScrollStateChanged" + state + "|");
    }

    private void doShare() {
        UmShare umShare = new UmShare(this, mBean.getTitle(), "", mBean.getCoverImages().get(0));
        umShare.Share(new UmShare.UmShareShareInterface() {
            @Override
            public void shareCallback() {
                ToastUtil.showLong("分享成功！");
            }

            @Override
            public void onShareFailed(String result) {

                ToastUtil.showLong("分享失败," + result);
            }
        });
    }

    public ComicsDetailBean getDetailBean() {
        return mBean;
    }

    public abstract static class AppBarStateChangeListener implements AppBarLayout.OnOffsetChangedListener {
        enum State {
            EXPANDED,
            COLLAPSED,
            IDLE
        }

        private State mCurrentState = State.IDLE;

        @Override
        public final void onOffsetChanged(AppBarLayout appBarLayout, int i) {
            if (i == 0) {
                if (mCurrentState != State.EXPANDED) {
                    onStateChanged(appBarLayout, State.EXPANDED);
                }
                mCurrentState = State.EXPANDED;
            } else if (Math.abs(i) >= appBarLayout.getTotalScrollRange()) {
                if (mCurrentState != State.COLLAPSED) {
                    onStateChanged(appBarLayout, State.COLLAPSED);
                }
                mCurrentState = State.COLLAPSED;
            } else {
                if (mCurrentState != State.IDLE) {
                    onStateChanged(appBarLayout, State.IDLE);
                }
                mCurrentState = State.IDLE;
            }
        }

        public abstract void onStateChanged(AppBarLayout appBarLayout, State state);
    }
}
